package com.pharmacy.MedicineManage.service;

import com.pharmacy.MedicineManage.dao.MedicineMapper;
import com.pharmacy.MedicineManage.entity.Medicine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class MedicineServiceImpl implements MedicineService {

    @Autowired
    private MedicineMapper medicineMapper;

    @Override
    public List<Medicine> getAllMedicines() {
        return medicineMapper.findAllMedicines();
    }

    @Override
    public Medicine getMedicineById(Integer id) {
        return medicineMapper.findMedicineById(id);
    }

    @Override
    public Medicine getMedicineByCode(String code) {
        return medicineMapper.findMedicineByCode(code);
    }

    @Override
    public List<Medicine> searchMedicinesByName(String name) {
        return medicineMapper.findMedicinesByName(name);
    }

    @Override
    public List<Medicine> getMedicinesByCategory(String category) {
        return medicineMapper.findMedicinesByCategory(category);
    }

    @Override
    @Transactional
    public boolean addMedicine(Medicine medicine) {
        // 检查药品编码是否已存在
        if (medicineMapper.findMedicineByCode(medicine.getCode()) != null) {
            return false;
        }
        medicine.setStatus(1);
        return medicineMapper.insertMedicine(medicine) > 0;
    }

    @Override
    @Transactional
    public boolean updateMedicine(Medicine medicine) {
        Medicine existing = medicineMapper.findMedicineByCode(medicine.getCode());
        if (existing != null && !existing.getId().equals(medicine.getId())) {
            return false; // 编码已被其他药品使用
        }
        return medicineMapper.updateMedicine(medicine) > 0;
    }

    @Override
    @Transactional
    public boolean deleteMedicine(Integer id) {
        return medicineMapper.deleteMedicine(id) > 0;
    }

    @Override
    public boolean isCodeExist(String code) {
        return medicineMapper.findMedicineByCode(code) != null;
    }
}